<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Promise发送AJAX</title>
  </head>
  <button>AJAX</button>

  <script>
    // http://api.xiaohigh.com/goods
    //获取按钮
    let btn = document.querySelector("button");

    //绑定事件
    btn.onclick = function () {
      //实例化对象
      let p = new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.responseType = "json";
        xhr.open("get", "http://api.xiaohigh.com/goods");
        xhr.send();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              //成功
              resolve(xhr.response);
            } else {
              //失败
              reject(xhr.status);
            }
          }
        };
      });
      //指定成功与失败的回调
      p.then(
        (v) => {
          console.log("请求成功, 响应体为");
          console.log(v);
        },
        (r) => {
          console.error(`请求失败, 响应状态码为 ${r}`);
        }
      );
    };
  </script>
  <body></body>
</html>
